using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Crm.SdkTypeProxy.Metadata;
using System;
using System.Net;

namespace Microsoft.Crm.Sdk.Utility
{
    public class CrmServiceUtility
    {
        public static CrmLabel CreateSingleLabel(string label, int langCode)
        {
            CrmNumber number = new CrmNumber();
            number.Value = langCode;
            LocLabel label2 = new LocLabel();
            label2.LanguageCode = number;
            label2.Label = label;
            CrmLabel label3 = new CrmLabel();
            label3.LocLabels = new LocLabel[] { label2 };
            return label3;
        }

        public static CrmService GetCrmService()
        {
            return GetCrmService(null, null);
        }

        public static CrmService GetCrmService(string organizationName)
        {
            return GetCrmService(null, organizationName);
        }

        public static CrmService GetCrmService(string crmServerUrl, string organizationName)
        {
            CrmAuthenticationToken token = new CrmAuthenticationToken();
            token.OrganizationName = organizationName;
            CrmService service = new CrmService();
            if ((crmServerUrl != null) && (crmServerUrl.Length > 0))
            {
                UriBuilder builder = new UriBuilder(crmServerUrl);
                builder.Path = "//MSCRMServices//2007//CrmService.asmx";
                service.Url = builder.Uri.ToString();
            }
            service.Credentials = CredentialCache.DefaultCredentials;
            service.CrmAuthenticationTokenValue = token;
            return service;
        }

        public static MetadataService GetMetadataService(string crmServerUrl, string organizationName)
        {
            CrmAuthenticationToken token = new CrmAuthenticationToken();
            token.OrganizationName = organizationName;
            MetadataService service = new MetadataService();
            if ((crmServerUrl != null) && (crmServerUrl.Length > 0))
            {
                UriBuilder builder = new UriBuilder(crmServerUrl);
                builder.Path = "//MSCRMServices//2007//MetadataService.asmx";
                service.Url = builder.Uri.ToString();
            }
            service.Credentials = CredentialCache.DefaultCredentials;
            service.CrmAuthenticationTokenValue = token;
            return service;
        }
    }
}
